<?php

/**
 * This is the model class for table "{{user}}".
 *
 * The followings are the available columns in table '{{user}}':
 * @property integer $id
 * @property string $username
 * @property string $password
 * @property string $email
 * @property string $home_page
 * @property integer $registered_time
 * @property integer $update_time
 * @property string $display_name
 * @property integer $status
 * @property integer $birthday
 * @property string $active_code
 * @property string $training_id
 * @property integer $is_validated
 * @property string $role
 * @property integer $sex
 * @property string $address
 * @property string $tel
 *
 * The followings are the available model relations:
 * @property Comments[] $comments
 * @property Files[] $files
 * @property Students[] $students
 * @property Video[] $videos
 * @property VideoRate[] $videoRates
 */
class User extends CActiveRecord
{
    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return User the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{user}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('username,display_name,email', 'required'),
            array('registered_time,sex, update_time, status, is_validated', 'numerical', 'integerOnly' => true),
            array('username', 'length', 'max' => 60),
            array('password', 'length', 'max' => 255),
            array('email', 'length', 'max' => 100),
            array('home_page', 'length', 'max' => 150),
            array('display_name', 'length', 'max' => 250),
            array('active_code', 'length', 'max' => 10),
            array('role', 'length', 'max' => 50),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, username, password, email, home_page, registered_time, update_time, display_name, status, active_code, is_validated, role', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'comments' => array(self::HAS_MANY, 'Comments', 'user_id'),
            'files' => array(self::HAS_MANY, 'Files', 'user_id'),
            'students' => array(self::HAS_MANY, 'Students', 'user_id'),
            'videos' => array(self::HAS_MANY, 'Video', 'user_id'),
            'videoRates' => array(self::HAS_MANY, 'VideoRate', 'user_id'),
            //'student' => array(self::MANY_MANY, 'GuitarClass', 'tbl_clstudent(class_id,student_id)'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'username' => 'Tài khoản',
            'password' => 'Mật khẩu',
            'email' => 'Email',
            'home_page' => 'Home Page',
            'registered_time' => 'Register Time',
            'update_time' => 'Update Time',
            'display_name' => 'Họ tên',
            'status' => 'Trạng thái',
            'active_code' => 'Mã kích hoạt',
            'is_validated' => 'Kích hoạt',
            'role' => 'Quyền',
            'birthday' => 'Ngày sinh',
            'sex' => 'Giới tính',
            'tel' => 'Điện thoại',
            'address' => 'Địa chỉ',
            'home_page' => 'Trang cá nhân',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('username', $this->username, true);
        $criteria->compare('password', $this->password, true);
        $criteria->compare('email', $this->email, true);
        $criteria->compare('home_page', $this->home_page, true);
        $criteria->compare('registered_time', $this->registered_time);
        $criteria->compare('update_time', $this->update_time);
        $criteria->compare('display_name', $this->display_name, true);
        $criteria->compare('status', $this->status);
        $criteria->compare('active_code', $this->active_code, true);
        $criteria->compare('is_validated', $this->is_validated);
        $criteria->compare('role', $this->role, true);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    public function validatePassword($pass)
    {
        return $this->password == $this->hashPassword($pass);
    }

    public function hashPassword($pass)
    {
        return md5($pass);
    }

    public function randomPw($length)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

        $size = strlen($chars);
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= $chars[rand(0, $size - 1)];
        }

        return $str;
    }

    public function beforeSave()
    {
        if ($this->isNewRecord) {
            $this->registered_time = time();
            $this->update_time = time();
        } else {
            $this->update_time = time();
        }
        return parent::beforeSave();
    }

    public function suggestUsername($keyword, $limit = 20)
    {
        $tags = $this->findAll(array(
            'condition' => 'username LIKE :keyword',
            'order' => 'username DESC, Username',
            'limit' => $limit,
            'params' => array(
                ':keyword' => '%' . strtr($keyword, array('%' => '\%', '_' => '\_', '\\' => '\\\\')) . '%',
            ),
        ));
        $names = array();
        foreach ($tags as $tag)
            $names[] = $tag->username;
        return $names;
    }
    
    public function checkOwn(){
        return $this->id == Yii::app()->user->id;
    }
}